<template lang="pug">
  .cart.head-page(v-if='isShow')
    HeadBar(title="购物车", @closeBar="closeCart")
    Scroll(:data="getCartList", v-if="getCartList")
      .cart-list
        .item(v-for="(item, index) in getCartList", :key="index")
          .choose
            .checkbox-name
            van-checkbox-group(v-model="checkedGoods", @change='changeSelect')
              van-checkbox(v-model='item.isSelected', :name="item.cartid", @change="changeItem(item.cartid, item.isSelected)")
          .thumb
            img(:src="item.productimgs[0].thumburl")
          .info.pos-r
            .title.omit {{item.name}}
            .desc.pos-a
            .extra.pos-a.tar
              .price ￥ {{item.price}}
              .subtotal.red ￥
                strong {{ Number((item.price * item.num * 100)/100).toFixed(2) }}
              van-stepper.count(v-model="item.num", :min="1", @change="changeCount(item)")
    .cart-foot(@click='handleCheckall', v-if="getCartList")
      van-checkbox(v-model='checkall', ref='checkall', @change='checkedAll') 全选
      .del-goods.red(@touchstart.stop.prevent='delCartGoods') 删除
      .money-wrap.tar
        span 合计：
        span.money ￥{{Number(totalPrice).toFixed(2) }}
      van-button(type='danger', @click.stop.prevent='onSubmit') 提交订单

    .empty-cart.tac.pos-r(v-if="!getCartList")
      .tip-box.pos-center
        i.iconfont.icon-cart
        p 你的购物车空空如也

</template>

<script>
import Scroll from 'Comps/Scroll'
import headBarMixin  from '@/mixins/headBar'
import autoSwitchSceneMixin  from '@/mixins/switch-scene'
import { mapGetters } from 'vuex'
let iBtn = false

export default {
  name: 'cart',
  mixins: [headBarMixin, autoSwitchSceneMixin],
  data() {
    return {
      isShow: false,
      checkall: true,
      cartData: null,
      checkedGoods: [],
      selectGoods: [],
      totalPrice: 0,
      isCheckAll: true, // 是否是点击全选checkbox
    }
  },
  mounted() {
    this.$vgo.on('cart:show', () => {
      this.isShow = true
      this.checkedGoods = []

      this.getCartList.map(item => {
        this.checkedGoods.push(item.cartid)
      })
      // 清除自动场景切换
      this.handleClearAutoSwitchScene()
      // 计算总价
      this.calcTotalMoney()
    })
  },
  computed: {
    ...mapGetters(['cartList']),
    getCartList() {
      if(this.cartList) {
        return this.cartList.list
      }
    }
  },
  methods: {
    // 单选
    changeSelect(val) {
      let checkedCount = val.length
      this.isCheckAll = false
      this.checkedGoods = val
      this.checkall = checkedCount === this.getCartList.length
      this.calcTotalMoney()
    },
    // 修改选中状态
    changeItem(cartId, stat) {
      this.isCheckAll = false
      this.$store.dispatch('changeGoodsStatus', {cartId: cartId, status: stat})
    },
    // 全选
    checkedAll() {
      if(this.checkall) {
        this.isCheckAll = true
        this.checkedGoods = []
        this.getCartList.map(item => {
          this.checkedGoods.push(item.cartid)
        })
      } else {
        if(this.isCheckAll) {
          this.checkedGoods = []
        }
      }
      this.calcTotalMoney()
    },
    handleCheckall() {
      this.isCheckAll = true
      this.$refs.checkall.toggle()
    },
    // 修改商品数量
    changeCount(val) {
      let num = 0
      let cartid

      this.getCartList.map(item => {
        num += item.num
        if(item.cartid == val.cartid) {
          cartid = item.cartid
        }
      })

      if(val.num > val.stock) {
        val.num = val.stock
        this.$vgo.tip('库存不足！')
        return
      }
      this.calcTotalMoney()
      // 更新购物车数据
      this.$store.dispatch('updateCartGoodsNum', [cartid, val.num])
    },
    // 删除商品
    delCartGoods() {
      // 阻止全选复选框选中
      this.isCheckAll = false
      console.log(this.checkedGoods.length)

      if(!this.checkedGoods.length) {
        this.$vgo.tip('请选择商品', 'fail')
        return
      }
      this.$vgo.open(() => {
        this.checkedGoods.map(item => {
          this.getCartList.map(goods => {
            if(item == goods.cartid) {
              this.$store.dispatch('deleteCartGoods', goods.cartid)
            }
          })
        })
      })
    },
    // 提交
    onSubmit() {
      this.isCheckAll = false

      if(this.checkedGoods.length <= 0) {
        this.$vgo.tip('未选择任何商品', 'fail')
        return
      }

      this.selectGoods = []
      this.checkedGoods.map(i => {
        this.getCartList.map(item => {
          if(i == item.cartid) {
            this.selectGoods.push(item)
          }
        })
      })

      this.$store.dispatch('fetchUserAddress')
      this.$vgo.emit('checkout', {goods: this.selectGoods, money: this.totalPrice})
      this.isShow = false
    },
    // 计算总价
    calcTotalMoney(){
      this.totalPrice = 0
      this.checkedGoods.map(item => {
        this.getCartList.map(g => {
          if(item == g.cartid) {
            this.totalPrice += Math.round(g.price * g.num * 100) / 100
          }
        })
      })
    },
    closeCart() {
      this.isShow = false
      this.handleRestartAutoSwitchScene()
    }
  },
  components: {
    Scroll
  }
}
</script>

<style lang="stylus">
@import '../../../assets/styles/color.styl'
.cart
  .cart-list
    box-sizing: border-box
    .item
      display: flex
      width: 100%
      margin-bottom: 10px
      padding: 10px
      background: $white-dark
      box-sizing: border-box
      .choose
        flex: 0 0 20px
        width: 20px
        line-height: 80px
        font-size: 0
        color: $success
      .thumb
        flex: 0 0 80px
        width: 60px
        padding: 0 10px
        img
          width: 100%
          height: 80px
      .info
        flex: 1
        max-width: 70%
        padding-right: 10px
        box-sizing: border-box
        .title
          height: 30px
          line-height: 30px
          font-size: 14px
          padding-right: 50px
          color: $black-dark
        .desc
          bottom: 0
          right: 0
          width: 100%
          height: 20px

          color: $black-light
        .extra
          right: 10px
          top: 4px
          font-weight: 700
          color: $black-light
          .subtotal
            margin-bottom: 10px
            strong
              font-size: 16px
          .red
            color: $danger
        .delete-btn
          right: 10px
          bottom: 0
  .van-submit-bar__bar
    padding-left: 10px
    .del-goods
      margin-left: 15px
      color: $danger
  .empty-cart
    display: flex
    justify-content: center
    align-items: center
    height: 100%
    font-size: 16px
    color: $black-light
    .tip-box
      i
        font-size: 60px
        color: $gray
      p
        margin: 10px auto
  .cart-foot
    display: flex
    align-items: center
    position: absolute
    left: 0
    right: 0
    bottom: 0
    padding-left: 15px
    height: 50px
    font-size: 14px
    background: #fff
    .del-goods
      margin-left: 10px
    .money-wrap
      flex: 1
      padding-right: 12px
      .money
        color: $danger
    .van-button
      border-radius: 0
      height: 100%
</style>
